# -*- coding: utf-8 -*-
"""
智慧职教MOOC视频下载器 - 日志管理模块
提供统一的日志记录和输出格式
"""

import logging
import os
from datetime import datetime
from pathlib import Path


class ColoredFormatter(logging.Formatter):
    """带颜色的日志格式化器"""
    
    COLORS = {
        'DEBUG': '\033[36m',    # 青色
        'INFO': '\033[32m',     # 绿色
        'WARNING': '\033[33m',  # 黄色
        'ERROR': '\033[31m',    # 红色
        'CRITICAL': '\033[35m', # 紫色
        'RESET': '\033[0m'      # 重置
    }
    
    def format(self, record):
        log_color = self.COLORS.get(record.levelname, self.COLORS['RESET'])
        record.levelname = f"{log_color}{record.levelname}{self.COLORS['RESET']}"
        return super().format(record)


class Logger:
    """日志管理类"""
    
    def __init__(self, name="MOOC下载器", log_level=logging.INFO, enable_file_log=True):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(log_level)
        
        # 避免重复添加处理器
        if self.logger.handlers:
            return
        
        # 控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(log_level)
        console_formatter = ColoredFormatter(
            '%(asctime)s [%(levelname)s] %(message)s',
            datefmt='%H:%M:%S'
        )
        console_handler.setFormatter(console_formatter)
        self.logger.addHandler(console_handler)
        
        # 文件处理器
        if enable_file_log:
            log_dir = Path("logs")
            log_dir.mkdir(exist_ok=True)
            
            log_file = log_dir / f"mooc_downloader_{datetime.now().strftime('%Y%m%d')}.log"
            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setLevel(log_level)
            file_formatter = logging.Formatter(
                '%(asctime)s [%(levelname)s] %(name)s: %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'
            )
            file_handler.setFormatter(file_formatter)
            self.logger.addHandler(file_handler)
    
    def debug(self, message):
        """调试信息"""
        self.logger.debug(message)
    
    def info(self, message):
        """一般信息"""
        self.logger.info(message)
    
    def warning(self, message):
        """警告信息"""
        self.logger.warning(message)
    
    def error(self, message):
        """错误信息"""
        self.logger.error(message)
    
    def critical(self, message):
        """严重错误"""
        self.logger.critical(message)
    
    def success(self, message):
        """成功信息（自定义）"""
        self.logger.info(f"✅ {message}")
    
    def failure(self, message):
        """失败信息（自定义）"""
        self.logger.error(f"❌ {message}")
    
    def progress(self, message):
        """进度信息（自定义）"""
        self.logger.info(f"🔄 {message}")


# 全局日志实例
logger = Logger() 